/**
 * 
 */
package hu.diploma.core.service.impl;

import hu.diploma.common.service.GroupService;
import hu.diploma.common.vos.GroupVo;
import hu.diploma.core.dao.GroupDao;
import hu.diploma.core.dao.PersonDao;
import hu.diploma.core.entity.BaseEntity;
import hu.diploma.core.entity.Group;
import hu.diploma.core.entity.Person;
import hu.diploma.core.util.transform.TransformUtil;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author zeleia
 * 
 */

@Service("GroupServiceImpl")
public final class GroupServiceImpl extends BaseServiceImpl<Group, GroupVo> implements GroupService {

	@Autowired
	public void setGenericDao(GroupDao dao) {
		super.setGenericDao(dao);
	}

	@Autowired
	PersonDao personDao;

	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public void addPersonToGroup(Long personId, Long groupId) throws Exception {
		Person person = personDao.findById(personId);
		Group group = getGenericDao().findById(groupId);
		group.getPeople().add(person);
		getGenericDao().merge(group);

	}

	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public void movePersonToGroup(Long personId, Long groupFromId, Long groupToId) throws Exception {
		Person person = personDao.findById(personId);
		Group groupFrom = getGenericDao().findById(groupFromId);
		Group groupTo = getGenericDao().findById(groupToId);

		groupFrom.getPeople().remove(person);
		groupTo.getPeople().add(person);

		getGenericDao().merge(groupFrom);
		getGenericDao().merge(groupTo);

	}

	@Override
	public void removePersonToGroup(Long personId, Long groupId) throws Exception {
		Person person = personDao.findById(personId);
		Group group = getGenericDao().findById(groupId);
		group.getPeople().remove(person);
		getGenericDao().merge(group);

	}

	@Override
	public List<GroupVo> findByDevice(Long id) throws Exception {

		return (List<GroupVo>) TransformUtil.entityToVo((BaseEntity) getGenericDao().loadAll());
	}

}
